package com.community.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.community.constant.JwtConstants;
import com.community.constant.TokenConstants;
import com.community.domain.enity.UserVo;
import com.community.domain.enity.vo.SendSmsVo;
import com.community.domain.response.JwtResponse;
import com.community.remote.SystemRemote;
import com.community.result.Result;
import com.community.service.UserLoginService;
import com.community.utils.JwtUtils;
import com.community.utils.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 类名称： UserLoginServiceImpl
 * 描述：
 * 创建人：zyj
 * 创建时间：2023/11/7 12:49
 */
@Service
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    SystemRemote systemRemote;

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Autowired
    RabbitMessagingTemplate rabbitMessagingTemplate;

    /**
     * 登录
     * @param userVo
     * @return
     */
    @Override
    public Result<JwtResponse> login(UserVo userVo) {

        Result<JwtResponse> result = null;

        Result<UserVo> resultFlag = systemRemote.loginByPassword(userVo);

        //获取数据
        UserVo userData = resultFlag.getData();


        if(null == userData){
            result = Result.error("账号不存在或密码错误");
            return result;
        }

        // 降级
        if(resultFlag.getCode() == Result.FAIL) {
            result = Result.error(resultFlag.getMsg());
            return result;
        }

        // 生成 token
        String userKey = UUID.randomUUID().toString().replaceAll("-", "");
        Map<String, Object> jwtMap = new HashMap<>();
        jwtMap.put(JwtConstants.USER_KEY, userKey);
        jwtMap.put(JwtConstants.DETAILS_USER_ID, userData.getId());
        String token = JwtUtils.createToken(jwtMap);

        // 存入redis
        redisTemplate.opsForValue().set(JwtConstants.SECRET + userKey, JSONObject.toJSONString(userData), 100, TimeUnit.MINUTES);
        JwtResponse jwtResponse = new JwtResponse();
        jwtResponse.setToken(token);
        jwtResponse.setExpireTime("100MIN");
        result = Result.success(jwtResponse);

        return result;
    }

    /**
     * 发送短信
     * @param sendSmsVo
     */
    @Override
    public void sendSms(SendSmsVo sendSmsVo) {

        rabbitMessagingTemplate.convertAndSend("community-direct","send.sms",JSONObject.toJSONString(sendSmsVo));

    }
}
